<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/administrator/AdministerPicture' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>公众监督数据列表</el-breadcrumb-item>
  </el-breadcrumb>
  <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      label-width="auto"
      :size="formSize"
      style="max-width: 96%; display: flex; flex-wrap: wrap;">
    <el-form-item label="所在省" style="margin-right: 20px;">
      <el-select
          v-model="ruleForm.province"
          placeholder="-全部-"
          @change="handleProvinceChange"
          style="width: 100px;"
      >
        <el-option
            v-for="province in provinces"
            :key="province.value"
            :label="province.label"
            :value="province.provinceId"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="所在市" prop="city" style="margin-right: 20px;">
      <el-select
          v-model="ruleForm.city"
          placeholder="-全部-"
          :disabled="!cities.length"
          style="width: 100px;"
      >
        <el-option
            v-for="(city,index) in cities"
            :key="city.value"
            :label="city.label"
            :value="city.cityId"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="预估等级" style="margin-right: 20px;">
      <el-select v-model="ruleForm.level" placeholder="选择等级" style="width: 100px;">
        <el-option v-for="(level,index) in levels" :key="level" :label="level" :value=index+1> </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="反馈起始日期" style="margin-right: 20px;">
      <el-date-picker v-model="ruleForm.date" type="date" placeholder="选择最早的反馈日期"></el-date-picker>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="fetchData">查询</el-button>
      <el-button type="danger" @click="resetQueryForm" style="margin-right: 20px;">清空</el-button>
    </el-form-item>
    <el-form-item>
      <el-radio-group v-model="ruleForm.assigned">
        <el-radio :label="true">已指派</el-radio>
        <el-radio :label="false">未指派</el-radio>
      </el-radio-group>
    </el-form-item>
  </el-form>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="feedbackId" label="编号" width="50"></el-table-column>
    <el-table-column prop="name" label="反馈者姓名"></el-table-column>
    <el-table-column prop="province" label="所在省"></el-table-column>
    <el-table-column prop="city" label="所在市"></el-table-column>
    <el-table-column prop="aqiLevel" label="预估污染等级"></el-table-column>
<!--    <el-table-column prop="date" label="反馈日期"></el-table-column>-->
    <el-table-column prop="time" label="反馈时间"></el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="mini" @click="check(scope.row)">查看</el-button>
        <el-button size="mini" type="danger" @click="assign(scope.row)">指派</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--  分页-->
  <div class="pagination-container">
    <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange">
    </el-pagination>
  </div>

</template>

<script setup>
import {reactive, ref, onMounted} from 'vue';
import axios from 'axios';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import {formatDate, getName} from "@/components/utils/addrUtils";

const provinces = ref([]);
const cities = ref([]);
const allCities = ref({});
const levels = ['一', '二', '三', '四', '五', '六'];

const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

const router = useRouter();
const formSize = ref('medium');
const ruleForm = reactive({
  province: '',
  city: '',
  level: '',
  date: '',
  assigned: ''
});
const loadProvinceCityData = async () => {
  try {
    const [provinceResponse, cityResponse] = await Promise.all([
      axios.get('/province_object.json'),
      axios.get('/city_object.json')
    ]);

    const provinceObject = provinceResponse.data;
    const cityObject = cityResponse.data;
    provinces.value = convertToProvinces(provinceObject);
    allCities.value = convertToCities(cityObject);
  } catch (error) {
    console.error('加载省市数据失败:', error);
  }
};
const convertToProvinces = (provinceObject) => {
  return Object.keys(provinceObject).map((provinceId, index) => ({
    value: index,//TODO 在这里添加对应id
    label: provinceObject[provinceId].name,
    provinceId: provinceId,
  }));
};
const convertToCities = (cityObject) => {
  //console.log(cityObject)
  const cities = {};
  Object.keys(cityObject).forEach((cityId, index) => {
    const city = cityObject[cityId];
    //const pid = cityObject[cityId]
    if (!cities[city.province]) {
      cities[city.province] = [];
    }
    //console.log(cityObject)
    cities[city.province].push({//下标改成id
      value: index,//TODO 在这里添加对应id
      label: city.name,
      cityId: cityId,

    });
  });
  //console.log(cities)
  return cities;//==allCities
};
const handleProvinceChange = (provinceIndex) => {
  //console.log(provinceIndex)
  //console.log(allCities.value['河北省'])
  //cities.value = allCities.value[provinces.value[provinceIndex].label] || [];
  //cities.value = allCities.value[provinceIndex]
  //console.log(provinces.value)
  provinces.value.forEach(p=>{
    //console.log(p.provinceId)
    if(p.provinceId == provinceIndex){
      cities.value = allCities.value[p.label]
    }
  })

};

// 在组件挂载时加载数据
onMounted(loadProvinceCityData);

const check = (row) => {
  router.push({
    path: '/administrator/AdministerData',//TODO 原本是query方法
    //name:'AdministerData',
    query: {formData: JSON.stringify(row)}
  });
  //console.log(row)
};

const assign = (row) => {
  router.push({
    path: '/administrator/AdministerDataAssign',
    query: {formData: JSON.stringify(row)}
  });
};

const fetchData = async () => {
  // Replace with your actual data fetching logic
  const response = await axios.get('http://localhost:8085/admin/queryFeedback', {
    params: {
      provinceId: ruleForm.province,
      cityId: ruleForm.city,
      aqiLevel: ruleForm.level,
      time: ruleForm.date,
      assign:ruleForm.assigned,
      //ruleForm,
      page: currentPage.value,
      pageSize: pageSize.value
    }
  });

  const sName = await axios.get('http://localhost:8085/supervisor/querySupervisorList',{
    params:{}
  })

  if(response.data.data!=null){
    getName().then(names=> {
      response.data.data.forEach(feedback => {
        //console.log('external loop')
        //console.log(feedback)
        feedback.time = formatDate(feedback.time);
        names.provinces.forEach(item => {
          if (feedback.provinceId == item.provinceId) {
            feedback.province = item.label;
          }
        })
        names.cities.forEach(item => {
          if (feedback.cityId == item.provinceId) {
            feedback.city = item.label;
          }
        })

        //为反馈查询并添加用户名等信息
        //console.log(sName)
        sName.data.data.forEach(supervisor=>{
          //console.log(feedback)
          //console.log(feedback.supervisorId,supervisor.supervisorId,feedback.supervisorId == supervisor.supervisorId)
          if(feedback.supervisorId == supervisor.supervisorId){
            feedback.name = supervisor.name
            feedback.supervisorInfo = supervisor
          }
        })

      })
      //console.log(response.data.data)
      ElMessage.success('查询成功！')
      tableData.value = response.data.data;
      //console.log(tableData.value)

    })
  }else {
    ElMessage.info('无查询结果！')
    tableData.value = response.data.data;
  }



  //console.log(response.data)
  if (response.data.data != null) {
    total.value = response.data.data.length
  }
};

const resetQueryForm = ()=>{
  //TODO
}

const isSwitchOn = ref(false);

function toggleSwitch() {
  isSwitchOn.value = !isSwitchOn.value;
}
</script>

<style scoped>
.demo-ruleForm {
  margin-right: 20px;
}

.el-breadcrumb {
  margin-bottom: 20px; /* 增加面包屑下方的间距 */
}

.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px; /* 或者你想要的高度 */
}
</style>